
import pika
import json

def publish_task_message(task_id, task_name, file_name,
                         exchange='demask_exchange', routing_key_prefix='demask.task'):
    try:
        connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
        channel = connection.channel()

        # 声明 topic 类型交换机（多次声明不会重复创建）
        channel.exchange_declare(exchange=exchange, exchange_type='topic', durable=True)

        routing_key = f"{routing_key_prefix}.{task_name.lower().replace(' ', '_')}"

        message = {
            'task_id': task_id,
            'task_name': task_name,
            'file_name': file_name
        }

        channel.basic_publish(
            exchange=exchange,
            routing_key=routing_key,
            body=json.dumps(message),
            properties=pika.BasicProperties(
                delivery_mode=2,  # 消息持久化
            )
        )

        connection.close()
        print(f"[x] 已发送任务到主题 {routing_key}，Exchange={exchange}")
    except Exception as e:
        print(f"[!] 发送任务失败：{e}")
